//
//  basedTVC.m
//  SeseNews
//
//  Created by lanou3g on 15/7/22.
//  Copyright (c) 2015年 Sese工作室. All rights reserved.
//
#define keyMessage @"gv",@"av",@"proid",@"os",@"vt",@"screen", @"publishid"
#define valueMessage @"4.6.1",@"0",@"ifengnews",@"ios_8.2",@"5",@"640x960",@"4002&uid=9e7ef1b49fbe48b041240ebb59955122a7c59657"
#define homePath  @"http://api.iclient.ifeng.com/ClientNews";
#import "basedTVC.h"
#import "MJRefresh.h"
#import "AFHTTPRequestOperation.h"
#import "model.h"
#import "oneImageTableViewCell.h"
#import "threeImageTableViewCell.h"
#import "tableHeaderView.h"
#import "SandBox.h"
#import "NetTools.h"
@interface basedTVC ()
@property(nonatomic,retain)NSMutableArray *headerImageArray;
@property(nonatomic,retain)NSMutableArray *itemArray;
@property(nonatomic,retain)NSMutableArray *headerArray;
@property(nonatomic,assign)BOOL update;
@property(nonatomic,strong)tableHeaderView *view1;
@property(nonatomic,assign)int i;
@property(nonatomic,retain)SandBox *sqlDH;
@property(nonatomic,retain)NSMutableArray *keyArray;
@property(nonatomic,retain)NSMutableArray *valueArray;

@end

@implementation basedTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建数据库操作的单例对象
    self.sqlDH = [SandBox sharedSqliteDataHandele];
    [self.sqlDH openSqlite];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.i=2;
    [self.tableView addHeaderWithTarget:self action:@selector(loadData)];
    self.view1=[[tableHeaderView alloc]initWithFrame:CGRectMake(0, 0, 375, 250)];
    self.tableView.tableHeaderView=self.view1;
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreData)];
    self.update=YES;
    self.itemArray=[NSMutableArray array];
    self.headerArray=[NSMutableArray array];
    
}
//启动软件进行刷新
-(void)viewWillAppear:(BOOL)animated{
    if (self.update==YES) {
        [self.tableView headerBeginRefreshing];
        self.update=NO;
    }
}
//.进行数据的请求
-(void)loadData
    {
        
        NSString *homeUrl=homePath;
        self.keyArray=[[NSMutableArray alloc]initWithObjects:keyMessage,nil];
        self.valueArray=[[NSMutableArray alloc]initWithObjects:valueMessage, nil];
        NSString *url1=[self.urlString componentsSeparatedByString:@"="][0];
        NSString *url2=[self.urlString componentsSeparatedByString:@"="][1];
        [self.keyArray addObject:url1];
        [self.valueArray addObject:url2];
        
        NSDictionary *dic=[[NSDictionary alloc]initWithObjects:self.valueArray forKeys:self.keyArray];
        [NetTools GET:homeUrl parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            
            // 数据解析
            [self parserData:responseObject  type:1];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"%@",error);
        }];
        
    }
//上拉刷新加载
-(void)loadMoreData{
    
    [self.keyArray addObject:@"page"];
    NSString *valueUrl=[[NSString alloc]initWithFormat:@"%d",self.i];
    [self.valueArray addObject:valueUrl];
    NSDictionary *dic=[[NSDictionary alloc]initWithObjects:self.valueArray forKeys:self.keyArray];
    NSString *homeUrl=homePath;
    [NetTools GET:homeUrl parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self parserData:responseObject type:2];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

    }
//公共方法.用来数据请求的如果是1就是第一页请求如果是二就是第二页请求。
-(void)loadDataForType:(int)type withURL:(NSString *)urlString{
    
        //拼接url
        NSURL *url=[NSURL URLWithString:urlString];
        NSURLRequest *request=[NSURLRequest requestWithURL:url];
        AFHTTPRequestOperation *operation=[[AFHTTPRequestOperation alloc]initWithRequest:request];
    //判断本地是否存在缓存数据如果有直接使用
    NSData *datasq = [self.sqlDH selectAllUrlString:urlString];
        if (0!=datasq) {
            [self locatReadData:datasq type:type];
        }
        else{
        //如何本地没有数据data就直接调用第三方进行数据请求。
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            [self judgeHeaderOrFootResh:operation type:type url:(NSString*)urlString];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
        }
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [queue addOperation:operation];
        
    }

//本地有数据后，调用此方法执行。
-(void)locatReadData:(NSData*)data type:(int)type{
//    [self parserData:data type:type];
}

//将block内容拿出来。方便判断本地文件。
//最新版
-(void)judgeHeaderOrFootResh:(AFHTTPRequestOperation*)operation type:(int)type url:(NSString*)urlString{
    NSString *html=operation.responseString;
    
    NSData *data=[html dataUsingEncoding:NSUTF8StringEncoding];
    
    //创建数据库操作的单例对象
    self.sqlDH = [SandBox sharedSqliteDataHandele];
    [self.sqlDH openSqlite];
    NSString *string = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    [self.sqlDH insertData:string UrlString:urlString];
    

}
//通过上面传下来了data，这里可能是本地保存的也可能是网路请求来的。
-(void)parserData:(NSArray*)data type:(int)type{
    if (type==1) {
        if (self.headerArray.count>0) {
            [self.headerArray removeAllObjects];
            [self getDataToArray:data];
        }else{
            [self getDataToArray:data];
        }
        [self getItemData:data];
        [self.tableView headerEndRefreshing];
        [self.tableView reloadData];
    }else{
        [self getItemData:data];
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
        self.i++;
        
    }

}
//创建两个方法分别进行解析数据，第一个用来解析下拉刷新
-(void)getDataToArray:(NSArray*)dicOrArray{
        if ([self.headerArray lastObject]!=nil) {
           [self.headerArray removeAllObjects];
        }
        NSDictionary *headerImageDic=[dicOrArray objectAtIndex:1];
        NSArray *headerImageItemArray=[headerImageDic objectForKey:@"item"];
        for (int i=0; i<headerImageItemArray.count; i++) {
            model *model1=[[model alloc]init];
            model1.currenPage=[headerImageDic objectForKey:@"currentPage"];
            [model1 addValueToModel:[headerImageItemArray objectAtIndex:i]];
                [self.headerArray addObject:model1];
        }
        self.view1.tableHeaderV=self.headerArray;
    }
    
-(void)getItemData:(NSArray*)dicOrArray{
        NSDictionary *itemDic=[dicOrArray objectAtIndex:0];
        NSArray *itemArray=[itemDic objectForKey:@"item"];
        for (int i=0; i<itemArray.count; i++) {
            model *model2=[[model alloc]init];
            model2.currenPage=[itemDic objectForKey:@"currentPage"];
            [model2 addValueToModel:[itemArray objectAtIndex:i]];
            [self.itemArray addObject:model2];
        }
        
    }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Return the number of rows in the section.
    return self.itemArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *indentifier=@"threeImageCell";
    static NSString *indentifier2=@"cell";
    model *model=[self.itemArray objectAtIndex:indexPath.row];
    threeImageTableViewCell *cell1=[tableView dequeueReusableCellWithIdentifier:indentifier];
    oneImageTableViewCell *cell2=[tableView dequeueReusableCellWithIdentifier:indentifier2];
    if (model.imageUrl1!=nil) {
        if (!cell1) {
            cell1=[[threeImageTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"threeImageCell"];
        }
        cell1.cellThreeModel=model;
        return cell1;
    }else {
        if (!cell2) {
            cell2=[[oneImageTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        }
        cell2.passValue=model;
        return cell2;
    }
    return nil;
}

#pragma mark -行高代理方法-
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        model *newModel=[self.itemArray objectAtIndex:indexPath.row];
        return [oneImageTableViewCell heightForRow:newModel];
    }


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
